<!doctype html>
<html>
<head>
    <!--[if lte IE 8]><script language="javascript" type="text/javascript" src="flot/excanvas.min.js"></script><![endif]-->
    <script language="javascript" type="text/javascript" src="vendor/jquery.min.js"></script>
    <script language="javascript" type="text/javascript" src="vendor/underscore.js"></script>
    <script language="javascript" type="text/javascript" src="vendor/backbone.js"></script>
    <script language="javascript" type="text/javascript" src="vendor/backbone-localstorage.js"></script>
</head>
<body>

<script type="text/javascript">
var ws;
var url;

var tests = {"9.1.1":1,"9.1.2":2,"9.1.3":3,"9.1.4":4,"9.1.5":5,"9.1.6":6};
var d2 = [["9.1.1",6021],["9.1.2",22146]];

var raw = {};

var d = [{data:[[0,6021],[2,22146]], label:"Autobahn",bars: { show: true }},{label:"WebSocket++",bars: { show: true },data:[[1,5243],[3,20042]]}];

var ws;

function connect() {
    url = wsperf.get('server');
    
    if ("WebSocket" in window) {
        ws = new WebSocket(url);
    } else if ("MozWebSocket" in window) {
        ws = new MozWebSocket(url);
    } else {
        document.getElementById("messages").innerHTML += "This Browser does not support WebSockets<br />";
        return;
    }
    ws.onopen = function(e) {
        console.log("Client: A connection to "+ws.URL+" has been opened.");
        
        wsperf.set('connected',true);
    };
    
    ws.onerror = function(e) {
        document.getElementById("messages").innerHTML += "Client: An error occured, see console log for more details.<br />";
        console.log(e);
        wsperf.set('connected',false);
    };
    
    ws.onclose = function(e) {
        console.log("Client: The connection to "+url+" was closed.");
        wsperf.set('connected',false);
    };
    
    ws.onmessage = function(e) {
        console.log(e.data);
        
        data = JSON.parse(e.data);
        
        if (data.type == "message") {
            console.log("Server: "+data.data);
        } else {
            if (raw[data.target] === undefined) {
                raw[data.target] = [data.data];
            } else {
                raw[data.target].push(data.data);
            }
            process();
        }
    };
}

function disconnect() {
    ws.close();
}

function send() {
    if (ws === undefined || ws.readyState != 1) {
        document.getElementById("messages").innerHTML += "Client: Websocket is not avaliable for writing<br />";
        return;
    }
    
    ws.send(document.getElementById("msg").value);
}

function process() {
    d = [];
    
    k = 0;
    
    for (i in raw) {
        o = {};
        
        
        o.label = i;
        o.bars = {show: true}
        
        o.data = [];
        
        for (j in raw[i]) {
            p = [k++,raw[i][j].microseconds];
            o.data.push(p);
        }
        
        d.push(o);
    }
    $.plot($("#placeholder"), d, {xaxis:[{tickFormatter: euroFormatter}]});
}

function euroFormatter(v, axis) {
    return tests[v];
}

$(function () {
    //$.plot($("#placeholder"), d, {xaxis:[{tickFormatter: euroFormatter}]});
    
    window.WSPerf = Backbone.Model.extend({
        defaults: function() {
            return {server:"ws://localhost:9003",connected:false};
        }
    });
    
    window.Server = Backbone.Model.extend({
        defaults: function() {
            return {enabled:true};
        }
    });
  
    window.ServerList = Backbone.Collection.extend({
        model: Server,
        localStorage: new Store("wsperf_servers"),
    });
    
    window.Servers = new ServerList;
    window.wsperf = new WSPerf;
    
    window.ServerView = Backbone.View.extend({
        tagName: "tr",
        
        template: _.template($('#server-template').html()),
        
        events: {
            "click td.clear" : "clear",
            "click td.server-enabled input" : "toggle_enabled"
        },
        
        initialize: function() {
            this.model.bind('change', this.render, this);
            this.model.bind('destroy', this.remove, this);
        },
        
        render: function() {
            $(this.el).html(this.template(this.model.toJSON()));
            this.setText();
            return this;
        },
        
        setText: function() {
            var ua = this.model.get('ua');
            var uri = this.model.get('uri');
            
            this.$('.server-ua').text(ua);
            this.$('.server-uri').text(uri);
        },
        
        remove: function() {
            console.log("remove");
            $(this.el).remove();
        },
        
        clear: function() {
            console.log("destroy");
            this.model.destroy();
        },
        
        toggle_enabled: function() {
            this.model.set('enabled',!this.model.get('enabled'));
        }
    });
    
    window.WSPerfSettingsView = Backbone.View.extend({
        tagName: "div",
        
        template: _.template($('#settings-template').html()),
        
        events: {
            "click #add-target-server": "addTargetServer",
            "click #target-server-table .clear-all": "clearAll",
            "click #toggle_connect": "toggle_connect"
        },
        
        initialize: function() {
            //this.model.bind('change', this.render, this);
            //this.model.bind('destroy', this.remove, this);
            wsperf.bind('change', this.render, this);
            
            Servers.bind('add', this.addOne, this);
            Servers.bind('reset', this.addAll, this);
            Servers.bind('all', this.render, this);
        },
        
        render: function() {
            $(this.el).html(this.template(wsperf.toJSON()));
            this.inputua = this.$("#add-target-server-ua");
            this.inputuri = this.$("#add-target-server-uri");
            this.addAll();
            return this;
        },
        
        addOne: function(server) {
            var view = new ServerView({model: server});
            $("#target-server-list").append(view.render().el);
        },
        
        addAll: function() {
            Servers.each(this.addOne);
        },
        
        addTargetServer: function() {
            var ua = this.inputua.val();
            var uri = this.inputuri.val();
            
            console.log("bar "+ua+" "+uri);
            
            if (!ua || !uri) {
                return;
            }
            
            Servers.create({ua: ua, uri: uri});
            
            this.inputua.val('');
            this.inputuri.val('');
        },
        
        clearAll: function() {
            console.log("foo");
            Servers.each(function(server) {server.destroy(); });
            return false;
        },
        
        toggle_connect: function() {
            if (wsperf.get('connected')) {
                disconnect();
            } else {
                connect();
            }
        }
    });
    
    window.WSPerfDataView = Backbone.View.extend({
        tagName: "div",
        
        template: _.template($('#data-template').html()),
        
        events: {
            //"click td.clear" : "clear"
        },
        
        initialize: function() {
            //this.model.bind('change', this.render, this);
            //this.model.bind('destroy', this.remove, this);
        },
        
        render: function() {
            $(this.el).html(this.template());
            return this;
        },
    });
    
    /*window.WSPerfCommanderView = Backbone.View.extend({
        el: $("#wsperf-commander"),
        
        events: {
            //"click #add-target-server": "addTargetServer",
            //"click #target-server-table .clear-all": "clearAll",
            //"click #menu-server-settings": "renderServerSettings",
            //"click #menu-server-settings": "renderServerSettings",
            //"click #menu-server-settings": "renderServerSettings",
        },
        
        initialize: function() {
            Servers.fetch();
        },
        
        render: function() {},
    });*/
    
    var WSPerfCommanderRouter = Backbone.Router.extend({
        initialize: function() {
            Servers.fetch();
            settingsView = new WSPerfSettingsView({el: "#content"});
            dataView = new WSPerfDataView({el: "#content"});
        },
        routes: {
            "/settings": "settings",
            "/data": "data",
            "*actions": "defaultRoute"
        },
        defaultRoute: function( actions ) {
            console.log(actions);
        },
        settings: function() {
            settingsView.render();
        },
        data: function() {
            dataView.render();
        }
    });
    
    var app_router = new WSPerfCommanderRouter;
    
    Backbone.history.start();
    
    //window.App = new WSPerfCommanderView;
});

</script>

<style>
body,html {
    margin: 0px;
    padding: 0px;
}
#controls {
    float:left;
    width:200px;
    background-color: #999;
}

#content {
    margin-left: 200px;
}

</style>

<div id="wsperf-commander">
<div id="controls">
    <ul>
        <li id="menu-server-settings"><a href="#/settings">Server Settings</a></li>
        <li id="menu-data-table"><a href="#/data">Data Table</a></li>
        <li id="menu-charts"><a href="#action">Charts</a></li>
    </ul>
    
    <div id="message_input"><input type="text" name="msg" id="msg" value="ws://localhost:9004" />
    <button onclick="send();">Send</button></div>
</div>
<div id="content">
    <div id="placeholder" style="width:600px;height:300px"></div>
    <div id="messages"></div>
</div>
</div>

<!-- Templates -->

<script type="text/template" id="server-template">
    <td class="server-enabled"><input type="checkbox"  <%= (enabled ? "checked" : "") %> /></td>
    <td class="server-ua"><%= ua %></td>
    <td class="server-uri"><%= uri %></td>
    <td class="clear">X</td>
</script>

<script type="text/template" id="settings-template">
    <h2>wsperf Server</h2>
    <div id="server">
    <input type="text" name="server_url" id="server_url" value="<%= server %>" <%= (connected ? "disabled" : "") %> />
    <button id="toggle_connect"><%= (connected ? "Disconnect" : "Connect") %></button>
    </div>
    
    <h2>Target Servers</h2>
    <table id="target-server-table">
    <thead>
    <th>Enabled</th><th>User Agent</th><th>URI</th><th class="clear-all">Remove</th>
    </thead>
    <tbody id="target-server-list"></tbody>
    </table>
    
    <div>
    User Agent: <input type="text" id="add-target-server-ua" /><br />
    URI: <input type="text" id="add-target-server-uri" /><br />
    <button id="add-target-server">Add Target Server</button>
    </div>
</script>

<script type="text/template" id="data-template">
    <div>data</div>
</script>

</body>
</html>